<template>
  <div class="login-container">
    <el-card>
      <h1>管理员登录</h1>
      <el-form :model="adminForm">
        <el-form-item label="账号" prop="username" clearable style="width: 300px;">
          <el-input v-model="adminForm.username" style="width: 240px" placeholder="请输入账号" clearable />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="adminForm.password" style="width: 240px" type="password" placeholder="请输入密码"
            show-password clearable/>
        </el-form-item>
        <el-form-item class="button-container">
          <div style="justify-content: space-between;">
          <el-button style="margin-left: 80px;" type="primary"  @click="login">登录</el-button>
          <el-button type="primary" @click="exit">返回</el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import axios from '@/utils/request'
import { removeToken, setToken } from '@/utils/auth';
import {useAdminRightsStore,adminAccount} from '@/store/index'
let rightsStore = useAdminRightsStore()
let accountStore = adminAccount()
const router = useRouter();
const adminForm = ref({
  username: '',
  password: ''
})
async function login() {
  try {
  const result = await axios.post('/admin/login', adminForm.value)
  if (result.data.code === 1) {
    router.push('/adminHome')
    //储存之前线移除
    removeToken()
    // 存储token
    setToken(result.data.data[0])
    // 存储权限
    rightsStore.$state.rights = result.data.data[1]
    //储存账号
    accountStore.$state.account = adminForm.value.username
    ElMessage.success('登录成功')
  } else {
    ElMessage.error('账号或密码错误')
  }
} catch (error) {
  console.error('登录失败:', error)
  ElMessage.error('登录失败，请稍后再试')
}
}

//回到首页
const exit = () => {
  router.push('/')
}
</script>

<style scoped>
.login-container {
  padding: 40px;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: beige;
  height: 100vh;
}

/* .el-form-item.button-container {
  position: relative;
}

.el-button {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
} */
</style>
